#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <fcntl.h>
#include <unistd.h>
#include <wait.h>


#include "../comm/util.hpp"
#include "../comm/Log.hpp"

namespace ns_runner
{
    using namespace ns_log;
    using namespace ns_util;

    class Runner
    {
    public:
        Runner() {}
        ~Runner() {}

        static void SetProcLimit(int _cpu_limit, int _mem_limit)
        {
            struct rlimit cpu_rlimit;
            cpu_rlimit.rlim_cur = _cpu_limit;
            cpu_rlimit.rlim_max = RLIM_INFINITY;
            setrlimit(RLIMIT_CPU, &cpu_rlimit);

            struct rlimit mem_rlimit;
            mem_rlimit.rlim_cur = _mem_limit;
            mem_rlimit.rlim_max = RLIM_INFINITY;
            setrlimit(RLIMIT_MEMLOCK, &mem_rlimit);
        }

        static int Run(const std::string &file_name, int cpu_limit, int mem_limit)
        {
            std::string _execute = PathUtil::Exe(file_name);
            std::string _stdin = PathUtil::Stdin(file_name);
            std::string _stdout = PathUtil::Stdout(file_name);
            std::string _stderr = PathUtil::Stderr(file_name);
            //std::cout << "_stdin: " << _stdin << std::endl;

            int _stdin_fd = open(_stdin.c_str(), O_CREAT | O_RDONLY, 0644);
            int _stdout_fd = open(_stdout.c_str(), O_CREAT | O_WRONLY, 0644);
            int _stderr_fd = open(_stderr.c_str(), O_CREAT | O_WRONLY, 0644);
            if (_stdin_fd < 0 || _stdout_fd < 0 || _stderr_fd < 0)
            {
                LOG(WARNING) << "打开文件失败" << "\n";
                return -1;
            }

            int id = fork();
            if (id < 0)
            {
                close(_stdin_fd);
                close(_stdout_fd);
                close(_stderr_fd);
                LOG(ERROR) << "没有形成子进程" << "\n";
                return -2;
            }
            else if (id == 0)
            {
                // child
                dup2(_stdin_fd, 0);
                dup2(_stdout_fd, 1);
                dup2(_stderr_fd, 2);

                SetProcLimit(cpu_limit, mem_limit);

                execl(_execute.c_str(), _execute.c_str(), nullptr);
                exit(1);
            }
            close(_stdin_fd);
            close(_stdout_fd);
            close(_stderr_fd);

            int status = 0;
            waitpid(id, &status, 0);
            LOG(INFO) << "运行完毕，status: " << (status & 0x7f) << std::endl;
            return (status & 0x7f);
        }
    };
}